package com.baiyang.app.tool.net;

import com.alibaba.fastjson.JSONObject;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;

/**
 * webSocket发送工具类
 * 使用单例模式
 */
public class MyWebSocketSendUtil {
    private static MyWebSocketSendUtil myWebSocketSendUtil ;
    public static void clear(){
        myWebSocketSendUtil = null;
    }
    //websocket客户端
    private OkHttpClient client;
    public static MyWebSocketSendUtil getWebSocket(){
        if(myWebSocketSendUtil == null){
            myWebSocketSendUtil = new MyWebSocketSendUtil();
        }
        return myWebSocketSendUtil;
    }
    public static void setUrl(String id){
        url = url + id;
    }
    private static String url = Urls.WS;
    private static WebSocketListener listener;

    public static void setListener(WebSocketListener listener) {
        MyWebSocketSendUtil.listener = listener;
    }

    private WebSocket webSocket;
    private MyWebSocketSendUtil(){
        client = new OkHttpClient();
        //2.创建Request对象，设置一个url地址（百度地址）,设置请求方式。
        Request request = new Request.Builder()
                .url(url)
                .build();
        webSocket = client.newWebSocket(request, listener);
    }
    public void send(Object object){
        webSocket.send(JSONObject.toJSONString(object));
    }
}
